import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';

class LanguageController extends GetxController {
  final _storage = GetStorage();
  final _storageKey = 'selected_language';
  
  var currentLanguage = 'zh_CN'.obs;
  
  final Map<String, Locale> supportedLanguages = {
    'zh_CN': Locale('zh', 'CN'), // 简体中文
    'zh_TW': Locale('zh', 'TW'), // 繁体中文
    'en_US': Locale('en', 'US'), // 英文
  };
  
  final Map<String, String> languageNames = {
    'zh_CN': '简体中文',
    'zh_TW': '繁體中文',
    'en_US': 'English',
  };
  
  @override
  void onInit() {
    super.onInit();
    _loadSavedLanguage();
  }
  
  void _loadSavedLanguage() {
    final savedLanguage = _storage.read(_storageKey) ?? 'en_US';
    currentLanguage.value = savedLanguage;
    _updateLocale();
  }
  
  void changeLanguage(String languageCode) {
    if (supportedLanguages.containsKey(languageCode)) {
      currentLanguage.value = languageCode;
      _storage.write(_storageKey, languageCode);
      _updateLocale();
    }
  }
  
  void _updateLocale() {
    final locale = supportedLanguages[currentLanguage.value]!;
    Get.updateLocale(locale);
  }
  
  String getCurrentLanguageName() {
    return languageNames[currentLanguage.value] ?? '简体中文';
  }
}